import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
function initStorage() {
    //检测当前的loaclStorage中是否拥有cart_data属性
    let flag = false;
    for (let i = 0; i < localStorage.length; i++) {
        if (localStorage.key(i) === "message") {
            flag = true;
            break;
        }
    }
    if (!flag) {
        localStorage.setItem("message", JSON.stringify([]));
    }
}
initStorage();
//从localStorage获取message
let message = localStorage.getItem("message");
export default new Vuex.Store({
    state: {
        // search: localStorage.getItem("obj")
        newBookData: [],
        message: JSON.parse(message),
        oneMes: [],
        // 点击传输数据渲染页面
        sortHtml: {}
    },

    mutations: {
        getnewBook(state, payload) {
            state.newBookData = payload;
        },
        getMessage(state, payload) {
            let newArr = state.message.filter(item => payload._id == item._id);
            if (!newArr.length) {
                state.message.push(payload);
                console.log(state.message);
                //刷新会丢失 存一份到localStorage
                localStorage.setItem("message", JSON.stringify(state.message));
            }
        },
        SET_SORT(state, item) {
            state.sortHtml = item;
        }
    },

    actions: {},
    getters: {
        // quchong: state => {
        //     let newArr = state.message.filter(
        //         item => state.oneMes._id == item._id
        //     );
        //     return newArr;
        // },
        setNewBook: state => {
            return state.newBookData.splice(0, 3);
        },
        setCover: state => {
            let bookCover = state.newBookData.splice(0, 3);
            for (let i = 0; i < bookCover.length; i++) {
                bookCover[i].cover = unescape(bookCover[i].cover.slice(7));
            }
            return bookCover;
        }
    }
});
